<?php

class Chat {

	public function unescape($str) {
		$str = rawurldecode($str);
		preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r);
		$ar = $r[0];
		foreach($ar as $k=>$v) {
			if(substr($v,0,2) == "%u")
			{
				$ar[$k] = iconv("UCS-2","utf-8//IGNORE",pack("H4",substr($v,-4)));
			}
			elseif(substr($v,0,3) == "")
			{
				$ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1)));
			}
			elseif(substr($v,0,2) == "&#")
			{
				echo substr($v,2,-1)."";
				$ar[$k] = iconv("UCS-2","utf-8",pack("n",substr($v,2,-1)));
			}
		}
		return join("",$ar);
	}
    //chat
	public function chatSend($data)
	{
		$data['content'] = $this->unescape($data['content']);

		$data['add_time'] = time();
		return $GLOBALS['db']->autoExecute('new_chat',$data);
	}
	public function chatGetOne($where='')
	{
		$sql = "select * from new_chat $where order by add_time desc";

		$data = $GLOBALS['db']->getRow($sql);
		if(!$data) return false;
		$data['content'] = preg_replace("#([^:]+回复[^:]+:)#","<b class='c_reply'>$1</b>",$data['content']);
		if($data)
		{
			$data['add_time'] = date("m-d H:i:s",$data['add_time']);
		}
		return $data;
	}
	public function chatGet($where='')
	{
		$sql = "select * from new_chat $where order by add_time asc";

		$data = $GLOBALS['db']->getAll($sql);
		foreach($data as $key=>$val)
		{
			$val['add_time'] = date("m-d H:i:s",$val['add_time']);
			$val['content'] = htmlspecialchars_decode($val['content']);
			$val['content'] = preg_replace("#([^:]+回复[^:]+:)#","<b class='c_reply'>$1</b>",$val['content']);
			$data[$key] = $val;
		}

		return $data;
	}
	public function chatStopUserGet(){
		$sql = "select user_name from new_chat_stop";
		$data = $GLOBALS['db']->getOne($sql);
		return $data;
	}

}
?>